package com.jbookshelf.beans;

import java.util.List;
import java.util.logging.Logger;

import org.primefaces.context.RequestContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.jbookshelf.dal.entities.Genres;
import com.jbookshelf.dal.providers.GenresDataProvider;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;

@Component
@Scope("request")
public class GenresBean {

	private Genres selectedGenre;
	private Genres newGenre;
	private List<Genres> genres;

	@Autowired
	GenresDataProvider dataprovider;

	public GenresBean() {
		newGenre = new Genres();
	}

	public List<Genres> getGenres() {
		if (genres == null) {
			this.genres = dataprovider.getGenres();
		}
		return genres;
	}

	public Genres getSelectedGenre() {
		return selectedGenre;
	}

	public void setSelectedGenre(Genres selectedGenre) {
		this.selectedGenre = selectedGenre;
	}

	public void setNewGenreName(String name) {
		this.newGenre.setName(name);
	}

	public String getNewGenreName() {
		return newGenre.getName();
	}

	public Genres getNewGenre() {
		return newGenre;
	}

	public void saveGenre() {

		if (dataprovider.getGenreByName(newGenre.getName()).size() != 0) {
			FacesContext.getCurrentInstance().addMessage(
					null,
					new FacesMessage(FacesMessage.SEVERITY_WARN,
							"This genre already exists",
							"Please enter a different genre"));
		} else {

			dataprovider.addGenres(newGenre);
		}
		final RequestContext context = RequestContext.getCurrentInstance();
		context.execute("createdlg.hide()");
		context.update("genres_list_form");

	}

	public void showCreateDialog() {

		final RequestContext context = RequestContext.getCurrentInstance();
		context.execute("createdlg.show()");
	}

	public void showEditDialog() {
		if (genres.contains(selectedGenre)) {
			final RequestContext context = RequestContext.getCurrentInstance();
			context.execute("editdlg.show()");
		} else {
			FacesContext context = FacesContext.getCurrentInstance();
			context.addMessage(null, new FacesMessage("Failed!",
					"No user selected!"));
		}
	}

	public void showViewDialog() {
		if (genres.contains(selectedGenre)) {
			final RequestContext context = RequestContext.getCurrentInstance();
			context.execute("viewdlg.show()");
		} else {
			FacesContext context = FacesContext.getCurrentInstance();
			context.addMessage(null, new FacesMessage("Failed!",
					"No user selected!"));
		}
	}

	public void closeSaveDialog() {

		final RequestContext context = RequestContext.getCurrentInstance();
		context.execute("createdlg.hide()");
		context.update("genres_list_form");
	}
}
